package com.iyao_app.im.nimsdk;

import android.text.TextUtils;

import com.iyao_app.im.nimsdk.utils.NimMessageSDK;
import com.iyaowoqu.base_library.util.LogUtil;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tongxue on 2017/12/17.
 */

public class MessageBoxSdk {

    private static List<IMMessage> emMessageList = new ArrayList<IMMessage>();
    private static Observer<List<IMMessage>> mIncomingMessageObserver;
    private static Observer<IMMessage> mMsgStatusObserver;
    private static String fromAccount;
    private static SessionTypeEnum msgType;

    /**
     * 注册消息状态监听
     *
     * 主页调取的这个方法
     */
    public static void observeMsgStatus() {

        observeReceiveMessage();

        mMsgStatusObserver = new Observer<IMMessage>() {
            @Override
            public void onEvent(IMMessage imMessage) {
                onMessageStatusChange(imMessage);
                LogUtil.e("oo",imMessage.toString());
            }
        };
        NimMessageSDK.observeMsgStatus(mMsgStatusObserver, true);
    }

    /**
     * 注册消息接收监听
     */
    private static void observeReceiveMessage() {
        mIncomingMessageObserver = new Observer<List<IMMessage>>() {

            @Override
            public void onEvent(List<IMMessage> imMessages) {

                if (imMessages == null || imMessages.isEmpty()) {
                    return;
                }
                for (IMMessage abc:imMessages){
                    fromAccount = abc.getFromAccount();
                    msgType = abc.getSessionType();
                }
            }
        };
        //观察消息
        NimMessageSDK.observeReceiveMessage(mIncomingMessageObserver, true);
    }

    private static int getItemIndex(String uuid) {
        for (int i = 0; i < emMessageList.size(); i++) {
            IMMessage message = emMessageList.get(i);
            if (TextUtils.equals(message.getUuid(), uuid)) {
                return i;
            }
        }
        return -1;
    }

    private static void onMessageStatusChange(IMMessage message) {
        int index = getItemIndex(message.getUuid());
        if (index >= 0 && index < emMessageList.size()) {
            IMMessage msg = emMessageList.get(index);
            msg.setStatus(message.getStatus());
            msg.setAttachStatus(message.getAttachStatus());
        }
    }

}
